﻿//store a list of available names for the autosuggest - make globally available
var mediaNames = [];

(function ($) {

    //Jquery plugin for our tree picker.
    $.fn.DigibizPicker = function (ctlId, umbPath, treeType, isCreateTree, selectStartNode, selectMultipleNodes, allowedExtensions, allowedMediaTypes, noAccessId, cropPropertyAlias, cropName, searchEnabled, autoSuggestEnabled, searchMethod, startNodeId) {

        var $tree = $(this);
        var ctl = $("#" + ctlId);
        var hiddenField = ctl.find("input[type='hidden']");
        var centerCol = ctl.find(".center");
        var leftCol = ctl.find(".left");
        var createCol = ctl.find(".create");
        var $searchTextBox = $(".searchtextbox");
        var throbber = null;

        //This is used to track collapsing of tree nodes due to the issue of the nodeClicked event being fired on tree collapse.
        var collapseNode = null;

        //store the selected tree node so that if the search is cancelled by inputting '' we will show the previous selected results
        var selectedTreeNode = null;

        //store a reference to the hidden field in the right columns data collection.
        centerCol.data("hiddenField", hiddenField);

        function nodeClickHandler(e, node) {

            //This is a dodgy hack due to a bug in the umb tree that fires the click event twice: http://umbraco.codeplex.com/workitem/29194.
            if ($(node).is(":hidden")) {
                collapseNode = node;
                return;
            }
            else {

                //If the collapseNode flag is null it's ok.
                if (!collapseNode) {
                    if (!isCreateTree) {
                        $searchTextBox.val("Search media...");
                        selectedTreeNode = node;
                        LoadAutoSuggest(false);
                        ShowCenter(node);
                    }
                    else {
                        ShowCreate(node);
                    }
                }
                else {
                    //Reset the flag but still do nothing.
                    collapseNode = null;
                }
            }
        }

        function treeSyncEventHandler() {

            //Re-add a handler to the tree's nodeClicked event.
            $tree.UmbracoTreeAPI().addEventHandler("nodeClicked", nodeClickHandler);
        }

        function DoHighlight(node) {
        	var div = $(node).find(">a>div");
            div.css("border", "1px solid #FBC2C4").css("background-color", "#FBE3E4").css("color", "#8a1f11");
            // read style first - do not remove - else might not work on some browsers
            setTimeout(function () { var style = div.attr('style'); div.removeAttr("style"); }, 250);
        }

        function ShowCreate(node) {

            //Get the node id of the node selected.
            var nodeId = $(node).attr("id");

            //Unless disabled
            if ($(node).hasClass("damp-nocreate")) {
                DoHighlight(node);
		        return;
		    }

            //Create a copy of the node clicked on the tree.
            var jNode = $(node).clone().find("a:first")

            //Clear the create div.
            createCol.html("")

            //Add the selected node to the div.
            createCol.append(jNode.html())

            //Store the id in the hiddenField.
            hiddenField.val(nodeId);
        }

        function ShowCenter(node) {

            //Get the node id of the node selected.
            var nodeId = $(node).attr("id");

            //Remove the ImageViewer element from the center that displays the previous elements
            centerCol.find(".imageViewer").remove();

            //Show a loading text.
            centerCol.append("<div class='loading'>Loading...</div>");

            //If there is no nodeId it means the top node wasn't loaded yet.
            if (!nodeId && !isCreateTree) {

                //Wait for 1200 miliseconds because if this code is hit the app pool probably is starting for the first time and we need to wait longer before we can click on the top node.
                setTimeout(
                    function () {
                        //Find the top node again and click it to show the allowed media items of the top node in the centre.
                        leftCol.find("a").first().click();
                    }, 1200);
            }

            $.ajax({
                type: "POST",
                async: false,
                url: umbPath + "/plugins/DigibizAdvancedMediaPicker/DigibizService.asmx/GetPickerData",
                data: '{ "nodeId": ' + parseInt(nodeId) + ', "allowedExtensions": "' + allowedExtensions + '", "allowedMediaTypes": "' + allowedMediaTypes + '", "cropPropertyAlias": "' + cropPropertyAlias + '", "cropName": "' + cropName + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {

                    var imgViewer = $("<div class='imageViewer'><span/></div>").appendTo(centerCol);

                    if (nodeId == noAccessId) {
                        imgViewer.find("span").append('<div class="noAccessId">You do not have permission for this media tree.</div>');
                    }
                    else {
                        var imgViewer;

                        var mediaItems = msg.d.mediaItems;
                        if (mediaItems.length != 0) {
                            for (var i in mediaItems) {
                                var html = '<div class="picker" onclick="javascript:AddToSelected(this, \'' + fixQuotes(mediaItems[i].mediaLink) + '\', \'' + selectMultipleNodes + '\');"><div class="picker-inner">' + mediaItems[i].mediaImageTag + '</div>';

                                html = html + '<p class="title" title="' + mediaItems[i].mediaName + '">' + mediaItems[i].mediaName + '</p></div>';

                                imgViewer.find("span").append(html);
                            }
                        }
                        else {
                            //Show a message no media items are available.
                            imgViewer.find("span").append('<div class="noMediaItems">There are no media items that can be selected.</div>');
                        }
                    }

                    // Add some hover classes to the picker div's   
                    imgViewer.find(".picker").hover(function () {
                        $(this).addClass('picker-over');
                    }, function () {
                        $(this).removeClass('picker-over');
                    });

                    //Remove the loading text after loading is complete.
                    centerCol.find("div.loading").remove();

                    imgViewer.show();

                    if (mediaItems.length == 1 && mediaItems[0].mediaId == parseInt(nodeId)) {

                        //Add the media item to the selected div.
                        AddToSelected(imgViewer.find("span div.picker"), '' + mediaItems[0].mediaLink + '', '' + selectMultipleNodes + '');
                    }
                }
            });
        }

        //Helper function used to escape quotes (') - see wi#16729
        function fixQuotes(s) {
            return s.replace("'", "\\'");
        }

        // Search the media section and displays results
        function Search(e) {
            e.preventDefault();

            var searchTerm = $searchTextBox.val();

            //if blank search is performed
            if (searchTerm == "Search media...") {
                //show center results for previous selected node
                ShowCenter(selectedTreeNode);
                return;
            }

            //selected node id to search under
            var searchNodeId = parseInt(startNodeId);
            if(searchMethod == "selected") {
                searchNodeId = parseInt($(selectedTreeNode).attr("id"));
            }

            $.ajax({
                type: "POST",
                async: false,
                url: umbPath + "/plugins/DigibizAdvancedMediaPicker/DigibizService.asmx/GetSearchData",
                data: '{ "searchTerm": "' + searchTerm + '", "nodeId": ' + searchNodeId + ', "allowedExtensions": "' + allowedExtensions + '", "allowedMediaTypes": "' + allowedMediaTypes + '", "cropPropertyAlias": "' + cropPropertyAlias + '", "cropName": "' + cropName + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var mediaItems = msg.d.mediaItems;
                    var imgViewer = $(".center .imageViewer");
                    imgViewer.find("span").html("");
                    //build results
                    if (mediaItems.length > 0) {
                        for (var i = 0; i < mediaItems.length; i++) {
                            var html = '<div class="picker" onclick="javascript:AddToSelected(this, \'' + fixQuotes(mediaItems[i].mediaLink) + '\', \'' + selectMultipleNodes + '\');"><div class="picker-inner">' + mediaItems[i].mediaImageTag + '</div>';

                            html = html + '<p class="title" title="' + mediaItems[i].mediaName + '">' + mediaItems[i].mediaName + '</p></div>';

                            imgViewer.find("span").append(html);
                        }
                        // Add some hover classes to the picker div's   
                        imgViewer.find(".picker").hover(function () {
                            $(this).addClass('picker-over');
                        }, function () {
                            $(this).removeClass('picker-over');
                        });
                    }
                    else {
                        imgViewer.find("span").append('<div class="noMediaItems">No results found.</div>');
                    }
                }
            });
        }

        function SuggestionClickEvent() {
            var suggestion = $(this).text();
            $searchTextBox.val(suggestion);
            jQuery(".searchbutton").trigger("click");
        }

        function LoadAutoSuggest(forceLoad) {
            //selected node id to search under
            var currentNodeId = parseInt(startNodeId);

            if(searchMethod == "selected" && selectedTreeNode != null) {
                currentNodeId = parseInt(jQuery(selectedTreeNode).attr("id"));
            }

            //if search is enabled and search is only under selected node otherwise if we're forceloading the autosuggest
            if((searchMethod == "selected" && searchEnabled) || forceLoad) {
                //load media names
                jQuery.ajax({
                    type: "POST",
                    async: true,
                    url: umbPath + "/plugins/DigibizAdvancedMediaPicker/DigibizService.asmx/GetMediaNames",
                    data: '{ "nodeId": ' + parseInt(currentNodeId) + ', "allowedExtensions": "' + allowedExtensions + '", "allowedMediaTypes": "' + allowedMediaTypes + '", "cropPropertyAlias": "' + cropPropertyAlias + '", "cropName": "' + cropName + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        mediaNames = msg.d;
                        $searchTextBox.autocomplete({
                            source: function (request, response) {
                                var results = $.ui.autocomplete.filter(mediaNames, request.term);
                                response(results.splice(0, 10));
                            },
                            max: 10
                        });
                    }
                });
            }
        }

        setTimeout(
            function () {
                //Add a handler to the tree's nodeClicked event.
                $tree.UmbracoTreeAPI().addEventHandler("nodeClicked", nodeClickHandler);
                $tree.UmbracoTreeAPI().addEventHandler("syncNotFound", treeSyncEventHandler);
                $tree.UmbracoTreeAPI().addEventHandler("syncFound", treeSyncEventHandler);
        }, 100);

        if(searchEnabled)
        {
            //add event handler for the search button
            jQuery(".searchbutton").click(Search);

            //if autosuggest is enabled - async load the names
            if (autoSuggestEnabled)
            {
                LoadAutoSuggest(true);
                //add event for autocomplete option click
                $(".ui-autocomplete li a").live("click", SuggestionClickEvent);
            }
        }

        if (!isCreateTree) {

            //Wait for 100 miliseconds because the Umbraco tree might not be loaded yet.
            setTimeout(
                function () {
                    //Find the top node and click it to show the allowed media items of the top node in the centre.
                    leftCol.find("a").first().click();
                }, 100);
        }
    }

})(jQuery);

/****
  Bind to control events
****/
jQuery(document).ready(function () {
    jQuery(".searchtextbox").focus(function () {
        if ($(this).val() == "Search media...") {
            $(this).val("");
        }
    }).blur(function () {
        if ($(this).val().length == 0) /*Small update*/
        {
            $(this).val("Search media...");
        }
    });
});